<template>
  <div class="document-container" data-v-cf3958bc>
    <div class="main-content">
      <!-- 左侧文档列表 -->
      <div class="document-list" :class="{ collapsed: isCollapsed }">
        <div class="list-header">
          <h2>
            <FileTextOutlined />
            <span>{{ categoryInfo?.title || '文档列表' }}</span>
          </h2>
          <a-button
            type="text"
            class="collapse-btn"
            @click="toggleCollapse"
          >
            <MenuFoldOutlined v-if="!isCollapsed" />
            <MenuUnfoldOutlined v-if="isCollapsed" />
          </a-button>
        </div>
        <div class="list-content">
          <a-spin :spinning="loading">
            <a-menu
              v-model:selectedKeys="selectedKeys"
              mode="inline"
              class="document-menu"
            >
              <a-menu-item
                v-for="doc in documents"
                :key="doc.slug"
                @click="handleDocumentClick(doc)"
              >
                {{ doc.title }}
              </a-menu-item>
            </a-menu>
          </a-spin>
        </div>
      </div>

      <!-- 固定的展开/收起按钮 -->
      <div 
        class="toggle-btn"
        :class="{ expanded: !isCollapsed }"
        @click="toggleCollapse"
      >
        <MenuUnfoldOutlined v-if="isCollapsed" />
        <MenuFoldOutlined v-else />
      </div>

      <!-- 中间文档内容 -->
      <div class="document-content">
        <div v-if="currentDocument" class="content-wrapper">
          <div class="document-header">
            <div class="document-meta">
              <span>
                <CalendarOutlined />
                {{ formatDate(currentDocument.created_at) }}
              </span>
              <span>
                <EyeOutlined />
                {{ currentDocument.views }} 次浏览
              </span>
              <span>
                <UserOutlined />
                {{ currentDocument.author }}
              </span>
            </div>
          </div>
          <div class="markdown-content" ref="contentRef">
            <MdPreview 
              :modelValue="renderedContent"
              :preview-theme="'github'"
              :code-theme="'github'"
              :show-code-row-number="true"
              :table-cell-max-width="800"
            />
          </div>
        </div>
        <div v-else class="empty-content">
          <a-empty description="请选择要查看的文档" />
        </div>
      </div>

      <!-- 右侧目录 -->
      <div class="document-toc" v-if="currentDocument && treeData.length > 0">
        <div class="toc-header">
          <h3>目录</h3>
        </div>
        <div class="toc-content">
          <a-tree
            :tree-data="treeData"
            :selectedKeys="selectedKeys"
            :expandedKeys="expandedKeys"
            @select="handleAnchorClick"
            @expand="handleTreeExpand"
            :showLine="{ showLeafIcon: false }"
            blockNode
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/preview.css'
import { 
  CalendarOutlined,
  EyeOutlined,
  UserOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  FileTextOutlined
} from '@ant-design/icons-vue'
import { documentApi } from '@/utils/api'
import { categoryApi } from '@/utils/api'

const route = useRoute()
const router = useRouter()
const documents = ref([])
const currentDocument = ref(null)
const loading = ref(false)
const categoryInfo = ref(null)
const parentCategory = ref(null)
const selectedKeys = ref([])
const contentRef = ref(null)
const headings = ref([])
const isCollapsed = ref(false)
const expandedKeys = ref([])

// 获取分类下的文档列表
const fetchDocuments = async () => {
  loading.value = true
  try {
    // 先获取分类信息
    const categoryRes = await categoryApi.getDetail(route.query.category)
    if (categoryRes.code === 0) {
      categoryInfo.value = categoryRes.data
    }

    // 获取文档列表
    const { code, data } = await documentApi.getList({
      category: route.query.category
    })
    if (code === 0) {
      documents.value = data.results
      // 如果有文档，根据URL参数选择文档
      if (data.results.length > 0) {
        const docSlug = route.query.doc
        if (docSlug) {
          const targetDoc = data.results.find(d => d.slug === docSlug)
          if (targetDoc) {
            handleDocumentClick(targetDoc)
          } else {
            handleDocumentClick(data.results[0])
          }
        } else {
          handleDocumentClick(data.results[0])
        }
      }
    }
  } catch (error) {
    message.error('获取文档列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取文档详情
const fetchDocument = async (slug) => {
  try {
    const { code, data } = await documentApi.getDetail(slug)
    if (code === 0) {
      currentDocument.value = data
      // 增加浏览量
      documentApi.addView(slug)
      // 等待内容渲染后解析文档结构
      nextTick(() => {
        setTimeout(parseDocumentStructure, 100)
      })
      // 初始化展开状态
      initExpandedKeys()
    }
  } catch (error) {
    message.error('获取文档失败')
    console.error(error)
  }
}

// 处理文档点击
const handleDocumentClick = (doc) => {
  selectedKeys.value = [doc.slug]
  fetchDocument(doc.slug)
  // 更新URL，但不重新加载页面
  router.replace({
    query: { ...route.query, doc: doc.slug }
  })
}

// 解析文档结构
const parseDocumentStructure = () => {
  // 使用正确的选择器
  const content = document.querySelector('.markdown-content .md-editor-preview')
  if (!content) {
    console.log('未找到内容元素，100ms后重试')
    setTimeout(parseDocumentStructure, 100)
    return
  }

  // 获取h2和h3标题
  const headingElements = content.querySelectorAll('h2, h3')
  const headingList = []

  headingElements.forEach((el, index) => {
    // 使用更可靠的ID生成方式
    const id = `heading-${index}-${el.textContent.trim().replace(/[^a-zA-Z0-9]/g, '-')}`
    el.id = id
    headingList.push({
      id,
      text: el.textContent.trim(),
      level: parseInt(el.tagName.charAt(1))
    })
  })

  headings.value = headingList
}

// 渲染Markdown内容
const renderedContent = computed(() => {
  if (!currentDocument.value?.content) return ''
  return currentDocument.value.content
})

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 监听路由变化
watch(
  () => route.query,
  (newQuery) => {
    if (newQuery.category) {
      fetchDocuments()
    }
  },
  { immediate: true }
)

// 初始化展开状态
const initExpandedKeys = () => {
  // 默认不展开任何节点
  expandedKeys.value = []
}

// 处理展开/收起
const handleTreeExpand = (keys, {expanded, node}) => {
  // 直接使用传入的 expandedKeys
  expandedKeys.value = [...keys]
}

// 处理树节点点击
const handleTreeClick = (e, node) => {
  // 如果节点有子节点，则切换展开状态
  if (node.dataRef?.children?.length > 0) {
    const key = node.key
    const index = expandedKeys.value.indexOf(key)
    if (index > -1) {
      expandedKeys.value = expandedKeys.value.filter(k => k !== key)
    } else {
      expandedKeys.value = [...expandedKeys.value, key]
    }
  }
  // 滚动到对应位置
  handleAnchorClick([node.key])
}

// 将标题列表转换为树形结构
const treeData = computed(() => {
  const tree = []
  const h2Map = new Map()
  
  headings.value.forEach((heading, index) => {
    const node = {
      title: heading.text,
      key: heading.id,
      isLeaf: heading.level === 3,
      switcherIcon: heading.level === 3 ? null : undefined,
      children: heading.level === 2 ? [] : undefined
    }
    
    if (heading.level === 2) {
      h2Map.set(heading.id, node)
      tree.push(node)
    } else if (heading.level === 3) {
      const lastH2 = Array.from(h2Map.values()).pop()
      if (lastH2) {
        lastH2.children.push(node)
      }
    }
  })
  
  // 移除没有子节点的 H2 标题的 children 数组
  tree.forEach(node => {
    if (node.children && node.children.length === 0) {
      delete node.children
      node.isLeaf = true
      node.switcherIcon = null
    }
  })
  
  return tree
})

// 处理目录项点击
const handleAnchorClick = (selectedKeys) => {
  if (!selectedKeys || selectedKeys.length === 0) return
  const id = selectedKeys[0]
  nextTick(() => {
    const element = document.getElementById(id)
    if (element) {
      // 平滑滚动到目标位置
      element.scrollIntoView({ 
        behavior: 'smooth',
        block: 'start'
      })
      // 添加高亮效果
      element.classList.add('anchor-highlight')
      setTimeout(() => {
        element.classList.remove('anchor-highlight')
      }, 2000)
    }
  })
}

// 监听文档内容变化
watch(
  () => currentDocument.value?.content,
  (newContent) => {
    if (newContent) {
      nextTick(() => {
        setTimeout(parseDocumentStructure, 100)
      })
    }
  }
)

// 组件挂载时初始化
onMounted(() => {
  // 移除这里的初始化，因为 watch 已经设置了 immediate: true
})

// 处理导航点击
const handleNavClick = (item) => {
  if (item.slug) {
    // 如果是一级目录，直接跳转到文档列表
    if (!item.parent_id) {
      router.push({
        path: '/document',
        query: { category: item.slug }
      }).catch(() => {
        // 如果是相同路由，忽略错误
        fetchDocuments()
      })
    }
  }
}

// 处理分类点击
const handleCategoryClick = (category) => {
  if (category && !category.parent_id) {
    router.push({
      path: '/document',
      query: { category: category.slug }
    }).catch(() => {
      // 如果是相同路由，忽略错误
      fetchDocuments()
    })
  }
}

// 添加折叠切换函数
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}
</script>

<style lang="less" scoped>
.document-container[data-v-cf3958bc] {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 64px);
  margin-top: 10px;
  background-color: var(--bg-color);
  padding: 0;
}

.main-content {
  display: flex;
  flex: 1;
  min-height: calc(100vh - 64px);
  margin: 0;
  padding: 0;
}

// 左侧文档列表
.document-list {
  position: relative;
  width: 280px;
  background: #fff;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  transition: all 0.3s;
  margin: 0;
  padding: 0;
  height: calc(100vh - 64px);
  overflow: hidden;

  &.collapsed {
    width: 0;
    padding: 0;
    margin: 0;
    border: none;
    overflow: hidden;
    
    .list-header, .list-content {
      opacity: 0;
      visibility: hidden;
    }
  }

  .list-header {
    padding: 16px;
    background: #fff;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h2 {
      margin: 0;
      font-size: 16px;
      display: flex;
      align-items: center;
      gap: 8px;
      color: #1f1f1f;
      font-weight: 500;

      .anticon {
        color: #8c8c8c;
      }
    }
  }

  .list-content {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
    
    .document-menu {
      border-right: none;
      
      :deep(.ant-menu-item) {
        height: 40px;
        line-height: 40px;
        margin: 4px 0;
        padding: 0 16px;
        border-radius: 4px;
        
        &:hover {
          color: #1890ff;
          background: rgba(24, 144, 255, 0.1);
        }
        
        &.ant-menu-item-selected {
          background: #e6f7ff;
          color: #1890ff;
          font-weight: 500;
        }
      }
    }
  }
}

// 中间文档内容
.document-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px 24px;
  background: #fff;
  margin: 0;
  min-width: 0;
  border-radius: 0;
  box-shadow: none;
  height: calc(100vh - 64px);
  
  .content-wrapper {
    max-width: 1000px;
    margin: 0 auto;
    
    .document-header {
      margin-bottom: 24px;
      
      .document-meta {
        color: #8c8c8c;
        display: flex;
        gap: 16px;
        
        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
    
    .markdown-content {
      font-size: 16px;
      line-height: 1.8;
      
      :deep(.md-editor-preview-wrapper) {
        padding: 0;
      }
      
      :deep(.md-editor-preview) {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
          'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
          'Noto Color Emoji';
      }

      :deep(.anchor-highlight) {
        background-color: rgba(255, 215, 0, 0.3);
        transition: background-color 0.3s ease;
      }
    }
  }
  
  .empty-content {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

// 右侧目录
.document-toc {
  width: 240px;
  background: #fff;
  border-left: 1px solid #f0f0f0;
  padding: 16px;
  margin: 0;
  border-radius: 0;
  height: calc(100vh - 64px);
  overflow-y: auto;

  .toc-header {
    margin-bottom: 16px;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #1f1f1f;
    }
  }

  .toc-content {
    overflow-y: auto;
  }
}

// 修改固定的展开/收起按钮样式
.toggle-btn {
  position: fixed;
  left: 0;
  top: 50vh;
  transform: translateY(-50%);
  z-index: 1000;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-left: none;
  border-radius: 0 4px 4px 0;
  padding: 8px 4px;
  cursor: pointer;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 40px;
  
  &:hover {
    color: #1890ff;
    background: rgba(24, 144, 255, 0.1);
  }

  &.expanded {
    left: 280px;
  }

  .anticon {
    font-size: 14px;
  }
}

:deep(.ant-tree-treenode) {
  width: 100%;
  
  .ant-tree-node-content-wrapper {
    width: calc(100% - 24px);
    
    .ant-tree-title {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style> 